$(function () {
    /**
     * 通用增加
     */
    $(".jr-add").click(function () {
        var $this = $(this);
        var url = $this.attr("url");
        win(url);
    });
    /**
     * 通用删除
     */
    $(".jr-remove").click(function () {
        var $this = $(this);
        var url = $this.attr("url");
        var grid = findGrid($this);
        var cks = null;
        if (grid.gridType == 'datagrid') {
            var cks = grid.datagrid("getChecked");
            if (cks.length <= 0) {
                alert("请选择要删除的项！");
                return false;
            }
            var rs = confirm("确定删除选中项吗？");
            if (!rs) {
                return false;
            }
            var idsArr = [];
            for (var i = 0; i < cks.length; i++) {
                if (typeof(cks[i].id) != 'undefined') {
                    idsArr.push(cks[i].id);
                }
            }
            var data = {
                ids: idsArr
            };
            if (idsArr.length > 0) {
                $.post(url, $.param(data, true), function (data) {
                    var rs = data;
                    if (rs.rs == 'error') {
                        alert(rs.tip);
                    } else if (rs.rs == 'fail') {
                        alert("服务器错误，删除失败，请稍后再试！");
                    } else {
                        for (var i = 0; i < cks.length; i++) {
                            var index = grid.datagrid("getRowIndex", cks[i]);
                            grid.datagrid("deleteRow", index);
                        }
                        grid.datagrid("reload");
                    }
                });
            }
        } else if (grid.gridType == 'treegrid') {
            var cks = grid.treegrid("getChecked");
            if (cks.length <= 0) {
                alert("请选择要删除的项！");
                return false;
            }
            var rs = confirm("确定删除选中项吗？");
            if (!rs) {
                return false;
            }
            var idsArr = [];
            for (var i = 0; i < cks.length; i++) {
                if (typeof(cks[i].id) != 'undefined') {
                    idsArr.push(cks[i].id);
                }
            }
            var data = {
                ids: idsArr
            };
            if (idsArr.length > 0) {
                $.post(url, $.param(data, true), function (data) {
                    var rs = data;
                    if (rs.rs == 'error') {
                        alert(rs.tip);
                    } else if (rs.rs == 'fail') {
                        alert("服务器错误，删除失败，请稍后再试！");
                    } else {
                        for (var i = 0; i < cks.length; i++) {
                            var index = grid.treegrid("getRowIndex", cks[i]);
                            grid.treegrid("deleteRow", index);
                        }
                        grid.treegrid("reload");
                    }
                });
            }
        }
    });
    /**
     * 通用排序
     */
    $(".jr-sort").click(function () {
        var $this = $(this);
        var $gird = findGrid($this);
        var sortUrl = $this.attr("url");
        jrwin(sortUrl, 600, 500);
    });
    /**
     * 通用打印
     */
    $(".jr-print").click(function () {

    });
    /**
     * 通用导出
     */
    $(".jr-export").click(function () {
        var $this = $(this);
        var grid = findGrid($this);
        var opt = grid.datagrid("options");
        var params = opt.queryParams;
        params.page = 1;
        params.rows = 100000;
        $.ajax({
            type: "post",
            async: true,
            url: opt.url,
            data: params,
            dataType: 'html',
            success: function (data) {
                var jtef = $("#exprotForm");
                if (jtef.length > 0) {
                    jtef.remove();
                }
                var formAction = $this.attr("url");
                var form = $('<form target="_self" action="' + formAction
                    + '" id="exprotForm" name="exprotForm" method="post"><input type="hidden" name="options" id="exprotFormOption" /><input type="hidden" name="fields" id="exprotFormField" /><input type="hidden" name="data" id="exprotFormData" /></form>');
                $("body").append(form);
                $("#exprotFormData").val(data);
                $("#exprotFormOption").val($this.attr("options"));
                var fields = [];
                var columns = opt.columns[0];
                for (var i = 0; i < columns.length; i++) {
                    if (typeof(columns[i].field) != 'undefined' && typeof(columns[i].checkbox) == 'undefined') {
                        fields.push(columns[i]);
                    }
                }
                $("#exprotFormField").val(JSON2.stringify(fields));
                $("#exprotForm").submit();
            }
        });
    });
    /**
     * 通用查询
     */
    $(".jr-search").click(function () {
        var $this = $(this);
        var grid = findGrid($this);
        id = grid.attr("id");
        var $cons = $("#" + id + "-cons");
        $cons.dialog("open");
        //再注册条件查询的回车事件
        $cons.find(".form-control").keypress(function (e) {
            if (e.keyCode == 13) {
                conditionSearch(id);
                return false;
            }
        });
    });

    $(".jr-edit-submit-close").click(function () {
        var $form = $("#jr-form");
        $form.form("submit", {
            url: $form.attr("action"),
            onSubmit: function () {
                var isVBool = isV($form.attr("id"));
                return isVBool;
            },
            success: function (data) {
                var rs = eval("[" + data + "]")[0];
                if (rs.rs == 'ok') {
                    alert("保存成功！");
                    window.close();
                }
            }
        });
    });

    $(".jr-edit-close").click(function () {
        window.close();
    });

    initUpload();

});

function initUpload() {
    $(".jr-upload").each(function () {
        var $this = $(this);
        var pick = "#" + $this.attr("id");
        var server = $this.attr("server");
        var uploader = WebUploader.create({
            swf: 'Uploader.swf',
            server: server,
            pick: pick,
            compress: false,
            chunked: false,
            chunkRetry: 3,
            method: 'post',
            duplicate: true,
            auto: true,
            accept: {
                extensions: 'gif,jpg,jpeg,png,bmp,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,doc,docx,xls,xlsx,ppt,pptx,zip,rar,gz,bz2,apk,ipa,pdf,mp4'
            }
        });

        uploader.on("startUpload", function () {
            var div = '<div class="jr-upload-loading">';
            div += '<div style="text-align: center;font-weight: bold;font-size: 16px;">文件上传中</div>';
            var files = uploader.getFiles();
            if (null != files && files.length > 0) {
                for (var i = 0; i < files.length; i++) {
                    div += '<div>' + files[i].name + '</div>';
                    div += '<div><input id="' + files[i].id + '" class="easyui-slider" data-options="showTip:true,min:0,max:100"></div>';
                }
            }
            div += '</div>';
            $("body").append(div);
            $.parser.parse('.jr-upload-loading');
        });

        uploader.on("uploadProgress", function (file, percentage) {
            $("#" + file.id).slider("setValue", parseInt((percentage * 100)), 10);
        });

        uploader.on("beforeFileQueued", function (file) {
            var rs = true;
            try {
                rs = doCallback(eval("jr" + $this.attr("id") + "BeforeFileQueued"), [file]);
            } catch (e) {
                rs = true;
            }
            return rs;
        });

        uploader.on("error", function (type) {
            try {
                doCallback(eval("jr" + $this.attr("id") + "Error"), [type]);
            } catch (e) {
                alert(type);
            }
        });
        uploader.on("uploadBeforeSend", function (object, data, headers) {
            var rs = true;
            try {
                rs = doCallback(eval("jr" + $this.attr("id") + "UploadBeforeSend"), [object, data, headers]);
            } catch (e) {
                rs = true;
            }
            return rs;
        });
        uploader.on("uploadSuccess", function (file, rs) {
            try {
                doCallback(eval($this.attr("id") + "UploadSuccess"), [file, rs]);
            } catch (e) {

            }
        });
        uploader.on("uploadError", function (file, reason) {
            alert(reason);
            try {
                doCallback(eval("jr" + $this.attr("id") + "UploadError"), [file]);
            } catch (e) {

            }
        });
        uploader.on("uploadFinished", function () {
            $(".jr-upload-loading").remove();
            uploader.reset();
        });
        uploader.on("uploadComplete", function (file) {
            try {
                doCallback(eval("jr" + $this.attr("id") + "UploadComplete"), [file]);
            } catch (e) {

            }
        });
    });

    $(".jr-upload-delete").click(function () {
        var $this = $(this);
        var $parent = $this.parent().parent().parent();
        var $img = $parent.find("img");
        var defaultImg = $img.attr("default");
        $img.attr("src", defaultImg);
        $parent.find(".jr-upload-img").val("");
    });

    $(".jr-upload-senior").click(function () {
        win($(this).attr("server"));
    });
}